package com.fromfuture.xuhuidoc.cordova.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.fromfuture.xuhuidoc.R;
import com.fromfuture.xuhuidoc.cordova.callback.OnImageSuccessListener;
import com.fromfuture.xuhuidoc.cordova.untils.ImageTask;
import com.fromfuture.xuhuidoc.cordova.view.SickImageview;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class SickRoomImageActivity extends AppCompatActivity {

    SickImageview imageView;
    final int MYRECRDD=1;
    private final static String ALBUM_PATH
            = "/sdcard/贯众云医/";
    private Bitmap mBitmap;
    private String mFileName="zp.JPEG";
    private String mSaveMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sick_room_image);

        imageView= (SickImageview) findViewById(R.id.sick_image);
        Intent intent=this.getIntent();
        String pic_url=intent.getStringExtra("pic_url");
        String pic_name=intent.getStringExtra("pic_name");
        mFileName=pic_name+".jpg";

        ImageTask task = new ImageTask(new OnImageSuccessListener() {

            @Override
            public void onImageSuccess(Bitmap bitmap) {
                imageView.setImageBitmap(bitmap);
                mBitmap=bitmap;
            }
        });
        task.execute(pic_url);

    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.sick_pic,menu);
//        return true;
//    }


    public void sick_room_savaPic(View v){
        storagepermission();//6.0动态权限
    }

//    @Override
//    public boolean onMenuItemSelected(int featureId, MenuItem item) {
//        storagepermission();//6.0动态权限
//        new Thread(saveFileRunnable).start();
//        return super.onMenuItemSelected(featureId, item);
//    }


    //saveFileRunnable调用的保存方法
    public void saveFile(Bitmap bm, String fileName) throws IOException {

        File dirFile = new File(ALBUM_PATH);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));

        try{
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        }catch (Exception e){
            Log.e("保存图片失败原因：",""+e);
        }

        bos.flush();
        bos.close();

    }
    //保存图片
    private Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                saveFile(mBitmap, mFileName);
                if (mBitmap==null){
                    mSaveMessage = "没有图片，保存失败！";
                }else {
                    mSaveMessage = "图片保存成功！\n 请在 文件管理/贯众云医 目录下查看...";
                }
            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };
    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(getApplication(), mSaveMessage, Toast.LENGTH_LONG).show();
        }
    };

    //6.0动态获取权限
    private void storagepermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED){
            new Thread(saveFileRunnable).start();
        }else {
            //需要申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    //如果权限允许了，则不会走下面
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MYRECRDD:
                if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {//点击允许后走下面,只走一次
                    // 获取权限成功。操作继续。
                    new Thread(saveFileRunnable).start();
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED){//点击拒绝后走下面，以后只要权限未开，就每次都走这个方法
                    Toast.makeText(this,"图片保存失败！"+"\n"+"贯众云医的存储权限被关闭，请在设置里打开存储权限",Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }
}
